"""
将奇林测试平台结果写入到研发管理平台测试计划中
备注：Authorization，Cookie需确认正确
test_result_path：需提前下载器林平台html格式测试结果并解压，拷贝url
planId：研发管理平台测试计划ID，通过url手动获取
"""

import re
import json
import requests
from requests_file import FileAdapter
from global_parameter import Authorization, Cookie


def get_kylin_test_result(test_result_path):
    """
    获取奇林测试结果
    :param test_result_path: 下载到本地并解压之后的的report路径
    :return:
    """
    s = requests.Session()
    s.mount('file://', FileAdapter())

    resp = s.get(test_result_path)
    content = resp.text

    match_data1 = re.findall(r'<td style="width:20%">.*?</td>', content)
    match_data2 = re.findall(r'<td style="width:10%">.*?</td>', content)

    # 用例名称列表
    case_name_list = []
    for data in match_data1:
        # print(data)
        case_name_list.append(data.split(">")[1].split("_")[0])

    # 用例结构列表
    case_result_list = []
    num = len(match_data1)
    for i in range(num):
        case_result_list.append(match_data2[5 * i + 2].split(">")[1].split("<")[0])

    print(case_name_list)
    print(case_result_list)

    # 如果用例测试了两次，使用字典去重机制，取最后一次用例的结果
    name_result_dict = {}
    assert len(case_name_list) == len(case_result_list)
    for index in range(len(case_name_list)):
        case_name = case_name_list[index]
        case_result = case_result_list[index]
        # print(case_name)
        # print(case_result)
        name_result_dict[case_name] = case_result
    print(name_result_dict)
    return name_result_dict


def get_yf_plan_testcases(planId):
    """
    获取研发管理平台用例对应关系
    :return:
    """
    headers = {"Accept": "application/json, text/plain, */*",
               "Accept-Encoding": "gzip, deflate",
               "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
               "Authorization": Authorization,
               "Connection": "keep-alive",
               "Content-Length": "73",
               "Content-Type": "application/json;charset=UTF-8",
               "Cookie": Cookie,
               "Host": "yf.oetsky.com",
               "Origin": "http://yf.oetsky.com",
               "Referer": "http://yf.oetsky.com/test/repo/1806580592308871169/case",
               "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0", }

    update_data = json.dumps({
        "searchType": "list",
        "size": 100,
        "current": 1,
        "planId": planId,
        "conditions": [
        ],
        "categoryIdentifier": "Task",
        "sortBy": {
            "name": "",
            "order": "",
            "type": ""
        }
    })
    res = requests.post("http://yf.oetsky.com/prod-api/dat-test/test/plan/case/pageList", headers=headers,
                        data=update_data)
    # print(res)
    # print(res.text)
    assert res.status_code == 200
    page = res.json().get("data").get("pages")
    print(page)
    list_case = []

    for i in range(page):
        update_data = json.dumps({
            "searchType": "list",
            "size": 100,
            "current": i + 1,
            "planId": planId,
            "conditions": [
            ],
            "categoryIdentifier": "Task",
            "sortBy": {
                "name": "",
                "order": "",
                "type": ""
            }
        })
        res = requests.post("http://yf.oetsky.com/prod-api/dat-test/test/plan/case/pageList", headers=headers,
                            data=update_data)
        # print(res.content)
        list_testcases = res.json().get("data").get("records")
        for testcase in list_testcases:
            list_case.append(
                {"id": testcase.get("id"), "subject": testcase.get("subject"), "code": testcase.get("code")})

    # print(list_case)
    print(len(list_case))
    return list_case


def updata_testcases(case_id, result):
    """
    研发管理平台更新单个用例
    :param update_data:
    :return:
    """
    headers = {"Accept": "application/json, text/plain, */*",
               "Accept-Encoding": "gzip, deflate",
               "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
               "Authorization": Authorization,
               "Connection": "keep-alive",
               "Content-Length": "73",
               "Content-Type": "application/json;charset=UTF-8",
               "Cookie": Cookie,
               "Host": "yf.oetsky.com",
               "Origin": "http://yf.oetsky.com",
               "Referer": "http://yf.oetsky.com/test/plancase/1825429523969040386/caseRepo",
               "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0", }

    update_data = json.dumps({"name": "operate_status", "id": case_id, "value": result})
    res = requests.put("http://yf.oetsky.com/prod-api/dat-test/test/plan/case/updateSingleField", headers=headers,
                       data=update_data)
    print(res)
    print(res.content)
    print(res.text)
    assert res.status_code == 200


def updata_cvt_case_result(test_result_path, planId):
    """
    更新cvt-b用例类型
    :return:
    """
    name_result_dict = get_kylin_test_result(test_result_path)
    list_case = get_yf_plan_testcases(planId)
    # print(list_case)

    dict_yf = {}
    for case in list_case:
        id = case.get("id")
        code = case.get("code")
        dict_yf[code] = id

    for name, result in name_result_dict.items():
        id = dict_yf.get(name)
        if result == "成功":
            yf_result = "已通过"
        elif result == "失败":
            yf_result = "未通过"
        else:
            assert False, "result错误：{}".format(result)
        updata_testcases(id, yf_result)


if __name__ == '__main__':
    test_result_path = "file:///C:/Users/zhaojinfan/Downloads/%E7%B5%82%E7%AB%AF%E9%A9%97%E6%94%B6115/report.html"
    planId = "1825429523969040386"
    updata_cvt_case_result(test_result_path, planId)
